/*
 * Copyright (c) 2014. kupat Corporation. All rights reserved.
 *  see statement on http://www.kupat.cn.
 */
package com.kfgj.hkp.common.dataaccess.dialect;

/**
 * Created by liwensihan on 2014/11/8.
 *
 * @author liwensihan
 */
public class OracleDialect extends AbstractDialect {

    @Override
    public boolean supportsLimit() {
        return true;
    }

    @Override
    public boolean supportsLimitOffset() {
        return true;
    }

    @Override
    public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
        sql = sql.trim();
        boolean isForUpdate = false;
        if ( sql.toLowerCase().endsWith(" for update") ) {
            sql = sql.substring( 0, sql.length()-11 );
            isForUpdate = true;
        }

        StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
        if (offset > 0) {
            pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
        }
        else {
            pagingSelect.append("select * from ( ");
        }
        pagingSelect.append(sql);
        if (offset > 0) {
//			int end = offset+limit;
            String endString = offsetPlaceholder+"+"+limitPlaceholder;
            pagingSelect.append(" ) row_ ) where rownum_ <= " + endString + " and rownum_ > " + offsetPlaceholder);
        }
        else {
            pagingSelect.append(" ) where rownum <= " + limitPlaceholder);
        }

        if ( isForUpdate ) {
            pagingSelect.append( " for update" );
        }

        return pagingSelect.toString();
    }
}
